package com.pai4j.zwiki.websocket.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

/**
 * ZWiki WebSocket握手拦截器
 * 
 * 功能：
 * 1. 在WebSocket握手前提取路径参数
 * 2. 验证参数有效性
 * 3. 将参数存储到WebSocket会话属性中
 * 4. 可以添加权限验证、Token验证等
 *
 * @author pai4j
 * @since 2025-10-14
 */
@Slf4j
public class ZWikiWebSocketInterceptor implements HandshakeInterceptor {

    /**
     * 握手前执行
     * 
     * 从请求路径中提取userId，并存储到session属性中
     * 路径格式：/zwiki-service/ws/notification/{userId}
     *
     * @param request HTTP请求
     * @param response HTTP响应
     * @param wsHandler WebSocket处理器
     * @param attributes WebSocket会话属性
     * @return true继续握手，false中断握手
     * @throws Exception 异常
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                                  WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 获取请求路径
        String path = request.getURI().getPath();
        
        log.debug("WebSocket握手请求. path: {}", path);

        try {
            // 解析路径，提取userId
            // 路径格式：/zwiki-service/ws/notification/{userId}
            String[] pathSegments = path.split("/");
            
            if (pathSegments.length < 5) {
                log.warn("WebSocket路径格式错误. path: {}", path);
                return false;
            }

            String userId = pathSegments[pathSegments.length - 1];

            // 验证userId
            if (userId == null || userId.trim().isEmpty()) {
                log.warn("WebSocket连接缺少userId参数. path: {}", path);
                return false;
            }

            // 将userId存储到session属性中
            attributes.put("userId", userId);
            
            // TODO: 可以在这里添加Token验证、权限验证等
            // String token = request.getHeaders().getFirst("Authorization");
            // if (!validateToken(token, userId)) {
            //     return false;
            // }

            log.info("WebSocket握手验证通过. userId: {}, path: {}", userId, path);
            return true;

        } catch (Exception e) {
            log.error("WebSocket握手处理失败. path: {}", path, e);
            return false;
        }
    }

    /**
     * 握手后执行
     * 
     * @param request HTTP请求
     * @param response HTTP响应
     * @param wsHandler WebSocket处理器
     * @param exception 握手过程中的异常（如果有）
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                              WebSocketHandler wsHandler, Exception exception) {
        if (exception != null) {
            log.error("WebSocket握手异常. path: {}", request.getURI().getPath(), exception);
        } else {
            log.debug("WebSocket握手完成. path: {}", request.getURI().getPath());
        }
    }
}

